package com.tomorrow.payments_hodgepodge.util;

import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Map;

/**
 * @author Tomorrow
 * @date 2020/1/18 16:33
 */
@Slf4j
public class HttpsUtils {
    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outStr        提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static String HttpsRequest(String requestUrl, String requestMethod, String outStr, Map<String, String> map) throws Exception {
        log.info("请求地址: {}", requestUrl);
        log.info("请求方式: {}", requestMethod);
        log.info("请求数据: {}", outStr);
//        创建 SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] trustManagers = {new MyX509TrustManager()};
//        初始化
        sslContext.init(null, trustManagers, new SecureRandom());
//        获取 sslSocketFactory 对象
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
//        设置当前实例使用

        StringBuffer buffer = null;
//      传递的URL
        URL url = new URL(requestUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//      请求方式
        connection.setRequestMethod(requestMethod);
//      请求头
        if (map != null) {
            for (String key : map.keySet()) {
                String value = map.get(key);
                connection.setRequestProperty(key, value);
            }
        }
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setSSLSocketFactory(sslSocketFactory);
        connection.connect();

        if (outStr != null) {
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(outStr.getBytes("utf-8"));
            outputStream.close();
        }

//        读取服务端内容
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        buffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            buffer.append(line);
        }
        String string = buffer.toString();
        log.info("返回数据: {}", string);
        return string;
    }

    public static void main(String[] args) throws Exception {
        String get = HttpsRequest("https://apis.map.qq.com/ws/location/v1/ip?ip=1000", "GET", null, null);
        System.out.println(get);
    }
}
